package com.lapelittle.order.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

/**
 * 商品数量转换器
 * 可以处理各种格式的数量输入，如：
 * - 纯数字: "100"
 * - 带单位: "100个"
 * - 带空格: " 100 "
 */
public class QuantityConverter implements Converter<Integer> {
    
    @Override
    public Class<Integer> supportJavaTypeKey() {
        return Integer.class;
    }
    
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }
    
    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                   GlobalConfiguration globalConfiguration) {
        String value = cellData.getStringValue();
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        
        // 使用“;”分割，将分割的值转为Integer并相加
        String[] values = value.split(";");
        int sum = 0;
        for (String v : values) {
            sum += Integer.parseInt(v);
        }
        return sum;
    }
    
    @Override
    public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
                                              GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(value == null ? "" : value.toString());
    }
} 